package com.vm.activity;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Timer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.RequestQueue;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.vm.commons.StringUtil;
import com.vm.commons.VMConst;
import com.vm.utils.MyTimerTask;
import com.vm.utils.MyVolley;
import com.wwtscapp.apk.R;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 
 * @ProjectName: [WeiMai]
 * @Author: [kent.wang]
 * @CreateDate: [2015年3月25日 上午8:58:58]
 * @Version: [v1.0]
 * 
 */
public class RegisterActivity extends Activity {

	private RequestQueue mQueue;
	int countDown = 90;
	private MyTimerTask mTimerTask;
	EditText et_username;
	EditText et_pass;
	// EditText et_pass2;
	EditText et_phone;
	// EditText et_email;
	EditText et_code;
	EditText et_invite;
	Button btn_register;
	Button btn_get_code;

	TextView tv_msg_username;
	TextView tv_msg_pass;
	// TextView tv_msg_email;
	TextView tv_msg_phone;
	TextView tv_msg_code;

	ImageView iv_right_username;
	ImageView iv_right_pass;
	// ImageView iv_right_pass2;
	// ImageView iv_right_email;
	ImageView iv_right_phone;
	ImageView iv_right_code;
	ImageView iv_right_invite;
	boolean isTrue_name = false;
	boolean isTrue_pass = false;
	// boolean isTrue_pass2 = false;
	// boolean isTrue_email = false;
	boolean isTrue_phone = false;
	boolean isTrue_code = false;
	boolean isTrue_invite = true;

	Timer timer;

	ImageView imgbtn_search_back;

	String username, password, phone, code, invite;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.register);

		mQueue = MyVolley.getRequestQueue();

		init();
	}

	public void init() {
		et_username = (EditText) findViewById(R.id.et_username);
		et_pass = (EditText) findViewById(R.id.et_pass);
		// et_pass2 = (EditText) findViewById(R.id.et_pass2);
		et_phone = (EditText) findViewById(R.id.et_phone);
		et_code = (EditText) findViewById(R.id.et_verification_code);
		et_invite = (EditText) findViewById(R.id.et_invite);
		btn_register = (Button) findViewById(R.id.btn_register);
		btn_get_code = (Button) findViewById(R.id.btn_get_verification_code);

		tv_msg_username = (TextView) findViewById(R.id.tv_msg_username);
		tv_msg_pass = (TextView) findViewById(R.id.tv_msg_pass);
		// tv_msg_pass2 = (TextView) findViewById(R.id.tv_msg_pass2);
		tv_msg_phone = (TextView) findViewById(R.id.tv_msg_phone);
		tv_msg_code = (TextView) findViewById(R.id.tv_msg_code);

		iv_right_username = (ImageView) findViewById(R.id.iv_right_username);
		iv_right_pass = (ImageView) findViewById(R.id.iv_right_pass);
		// iv_right_pass2 = (ImageView) findViewById(R.id.iv_right_pass2);
		iv_right_phone = (ImageView) findViewById(R.id.iv_right_phone);
		iv_right_code = (ImageView) findViewById(R.id.iv_right_code);
		iv_right_invite = (ImageView) findViewById(R.id.iv_right_invite);
		btn_get_code.setOnClickListener(getCodeListener);
		btn_register.setOnClickListener(btnClickListener);

		// et_username.setOnFocusChangeListener(focusChangeListener);
		// et_pass.setOnFocusChangeListener(focusChangeListener);
		// et_pass2.setOnFocusChangeListener(focusChangeListener);
		// et_phone.setOnFocusChangeListener(focusChangeListener);
		// et_code.setOnFocusChangeListener(focusChangeListener);

		imgbtn_search_back = (ImageView) findViewById(R.id.imgbtn_search_back);
		imgbtn_search_back.setOnClickListener(btn_backListener);
	}

	public void validateText(View v) {
		String msg = null;
		String url = null;
		switch (v.getId()) {
		case R.id.et_username:
			// tv_msg_username.setText("hasFocus=false");
			username = et_username.getText().toString();
			if (username == null || username.equals("")) {
				msg = "请输入用户名";
				isTrue_name = false;
				// tv_msg_username.setText(msg);
				// tv_msg_username.setVisibility(View.VISIBLE);
				iv_right_username.setVisibility(View.GONE);
			} else if (!isLetterDigitOrChinese(username)) {
				msg = "用户名只能由数字和字母组成";
				tv_msg_username.setVisibility(View.VISIBLE);
				tv_msg_username.setText(msg);
				isTrue_name = false;
				iv_right_username.setVisibility(View.GONE);
			}
			// 验证用户名是否存在
			else {
				url = VMConst.REQUEST_URL + "checkname?username=" + username;
				StringRequest stringRequest = new StringRequest(url,
						new Listener<String>() {
							@Override
							public void onResponse(String arg0) {
								// TODO Auto-generated method stub
								if (arg0.contains("可用")) {
									isTrue_name = true;
									tv_msg_username.setVisibility(View.GONE);
									iv_right_username
											.setVisibility(View.VISIBLE);
								} else {
									isTrue_name = false;
									tv_msg_username.setText(arg0.toString());
									tv_msg_username.setVisibility(View.VISIBLE);
									iv_right_username.setVisibility(View.GONE);
								}

							}
						}, null);
				mQueue.add(stringRequest);
			}

			break;
		case R.id.et_pass:
			password = et_pass.getText().toString();
			if (password == null || password.equals("")) {
				msg = "请输入密码";
				isTrue_pass = false;
				// tv_msg_pass.setText(msg);
				// tv_msg_pass.setVisibility(View.VISIBLE);
				iv_right_pass.setVisibility(View.GONE);
			} else {
				isTrue_pass = true;
				tv_msg_pass.setVisibility(View.GONE);
				iv_right_pass.setVisibility(View.VISIBLE);
			}
			break;
		// case R.id.et_pass2:
		// pass2 = et_pass2.getText().toString();
		// if (pass2 == null || pass2.equals("")) {
		// msg = "两次密码输入不一致";
		// isTrue_pass2 = false;
		// tv_msg_pass2.setText(msg);
		// tv_msg_pass2.setVisibility(View.VISIBLE);
		// iv_right_pass2.setVisibility(View.GONE);
		// } else {
		// if (pass2.equals(password)) {
		// isTrue_pass2 = true;
		// tv_msg_pass2.setVisibility(View.GONE);
		// iv_right_pass2.setVisibility(View.VISIBLE);
		// } else {
		// msg = "两次密码输入不一致";
		// isTrue_pass2 = false;
		// tv_msg_pass2.setText(msg);
		// tv_msg_pass2.setVisibility(View.VISIBLE);
		// iv_right_pass2.setVisibility(View.GONE);
		// }
		// }
		// break;

		case R.id.et_phone:
			phone = et_phone.getText().toString();
			if (phone == null || phone.equals("")) {
				msg = "请输入手机号";
				isTrue_phone = false;
				// tv_msg_phone.setText(msg);
				// tv_msg_phone.setVisibility(View.VISIBLE);
				iv_right_phone.setVisibility(View.GONE);
			} else {
				if (!isMobileNO(phone)) {
					msg = "请输入正确手机号";
					isTrue_phone = false;
					tv_msg_phone.setText(msg);
					tv_msg_phone.setVisibility(View.VISIBLE);
					iv_right_phone.setVisibility(View.GONE);
				} else {

					url = VMConst.REQUEST_URL + "checkMobilePhone?phone="
							+ phone;
					StringRequest stringRequest = new StringRequest(url,
							new Listener<String>() {
								@Override
								public void onResponse(String arg0) {
									// TODO Auto-generated method stub
									if (arg0.contains("可")) {
										isTrue_phone = true;
										tv_msg_phone.setVisibility(View.GONE);
										iv_right_phone
												.setVisibility(View.VISIBLE);
									} else {
										isTrue_phone = false;
										tv_msg_phone.setText(arg0.toString());
										tv_msg_phone
												.setVisibility(View.VISIBLE);
										iv_right_phone.setVisibility(View.GONE);
									}

								}
							}, null);
					mQueue.add(stringRequest);
				}
			}
			break;

		case R.id.et_verification_code:
			code = et_code.getText().toString();
			if (code == null || code.equals("")) {
				msg = "请输入验证码";
				isTrue_code = false;
				// tv_msg_code.setText(msg);
				// tv_msg_code.setVisibility(View.VISIBLE);
				iv_right_code.setVisibility(View.GONE);
			} else {
				// 验证验证码
				url = VMConst.REQUEST_URL + "checkCode?phone=" + phone
						+ "&code=" + code;
				StringRequest stringRequest = new StringRequest(url,
						new Listener<String>() {
							@Override
							public void onResponse(String arg0) {
								// TODO Auto-generated method stub
								if (arg0.contains("正确")) {
									isTrue_code = true;
									tv_msg_code.setVisibility(View.GONE);
									iv_right_code.setVisibility(View.VISIBLE);
								} else {
									isTrue_code = false;
									tv_msg_code.setText(arg0.toString());
									tv_msg_code.setVisibility(View.VISIBLE);
									iv_right_code.setVisibility(View.GONE);
								}

							}
						}, null);
				mQueue.add(stringRequest);
			}
			break;
		case R.id.et_invite:
			invite = et_invite.getText().toString();
			if (invite == null) {
				invite = "";
				isTrue_invite = true;
			} else {
				url = VMConst.REQUEST_URL + "checkInvCode?invCode=" + invite;
				StringRequest stringRequest = new StringRequest(url,
						new Listener<String>() {
							@Override
							public void onResponse(String arg0) {
								// TODO Auto-generated method stub
								if (arg0.contains("存在")) {
									isTrue_invite = true;
									iv_right_invite.setVisibility(View.VISIBLE);
								} else {
									isTrue_invite = false;
								}

							}
						}, null);
				mQueue.add(stringRequest);
			}
			break;
		default:
			break;
		}
	}

	OnFocusChangeListener focusChangeListener = new OnFocusChangeListener() {

		@Override
		public void onFocusChange(View v, boolean hasFocus) {
			String url = null;
			switch (v.getId()) {
			case R.id.et_username:
				// 失去焦点
				if (!hasFocus) {
					// tv_msg_username.setText("hasFocus=false");
					username = et_username.getText().toString();
					if (username == null || username.equals("")) {
						isTrue_name = false;
						// tv_msg_username.setText(msg);
						// tv_msg_username.setVisibility(View.VISIBLE);
						iv_right_username.setVisibility(View.GONE);
					} else if (!isLetterDigitOrChinese(username)) {
						tv_msg_username.setVisibility(View.VISIBLE);
						tv_msg_username.setText("用户名只能由数字和字母组成");
						isTrue_name = false;
						iv_right_username.setVisibility(View.GONE);
					}
					// 验证用户名是否存在
					else {
						url = VMConst.REQUEST_URL + "checkname?username="
								+ username;
						StringRequest stringRequest = new StringRequest(url,
								new Listener<String>() {
									@Override
									public void onResponse(String arg0) {
										// TODO Auto-generated method stub
										if (arg0.contains("可用")) {
											isTrue_name = true;
											tv_msg_username
													.setVisibility(View.GONE);
											iv_right_username
													.setVisibility(View.VISIBLE);
										} else {
											isTrue_name = false;
											tv_msg_username.setText(arg0
													.toString());
											tv_msg_username
													.setVisibility(View.VISIBLE);
											iv_right_username
													.setVisibility(View.GONE);
										}

									}
								}, null);
						mQueue.add(stringRequest);
					}
				}
				break;
			case R.id.et_pass:
				if (!hasFocus) {
					password = et_pass.getText().toString();
					if (password == null || password.equals("")) {
						isTrue_pass = false;
						// tv_msg_pass.setText(msg);
						// tv_msg_pass.setVisibility(View.VISIBLE);
						iv_right_pass.setVisibility(View.GONE);
					} else {
						isTrue_pass = true;
						tv_msg_pass.setVisibility(View.GONE);
						iv_right_pass.setVisibility(View.VISIBLE);
					}
				}
				break;
			// case R.id.et_pass2:
			// if (!hasFocus) {
			// pass2 = et_pass2.getText().toString();
			// if (pass2 == null || pass2.equals("")) {
			// msg = "两次密码输入不一致";
			// isTrue_pass2 = false;
			// tv_msg_pass2.setText(msg);
			// tv_msg_pass2.setVisibility(View.VISIBLE);
			// iv_right_pass2.setVisibility(View.GONE);
			// } else {
			// if (pass2.equals(password)) {
			// isTrue_pass2 = true;
			// tv_msg_pass2.setVisibility(View.GONE);
			// iv_right_pass2.setVisibility(View.VISIBLE);
			// } else {
			// msg = "两次密码输入不一致";
			// isTrue_pass2 = false;
			// tv_msg_pass2.setText(msg);
			// tv_msg_pass2.setVisibility(View.VISIBLE);
			// iv_right_pass2.setVisibility(View.GONE);
			// }
			// }
			// }
			// break;

			case R.id.et_phone:
				if (!hasFocus) {
					phone = et_phone.getText().toString();
					if (phone == null || phone.equals("")) {
						isTrue_phone = false;
						// tv_msg_phone.setText(msg);
						// tv_msg_phone.setVisibility(View.VISIBLE);
						iv_right_phone.setVisibility(View.GONE);
					} else {
						url = VMConst.REQUEST_URL + "checkMobilePhone?phone="
								+ phone;
						StringRequest stringRequest = new StringRequest(url,
								new Listener<String>() {
									@Override
									public void onResponse(String arg0) {
										// TODO Auto-generated method stub
										if (arg0.contains("可")) {
											isTrue_phone = true;
											tv_msg_phone
													.setVisibility(View.GONE);
											iv_right_phone
													.setVisibility(View.VISIBLE);
										} else {
											isTrue_phone = false;
											tv_msg_phone.setText(arg0
													.toString());
											tv_msg_phone
													.setVisibility(View.VISIBLE);
											iv_right_phone
													.setVisibility(View.GONE);
										}

									}
								}, null);
						mQueue.add(stringRequest);
					}
				}
				break;

			case R.id.et_verification_code:
				if (!hasFocus) {
					code = et_code.getText().toString();
					if (code == null || code.equals("")) {
						isTrue_code = false;
						// tv_msg_code.setText(msg);
						// tv_msg_code.setVisibility(View.VISIBLE);
						iv_right_code.setVisibility(View.GONE);
					} else {
						// 验证验证码
						url = VMConst.REQUEST_URL + "checkCode?phone=" + phone
								+ "&code=" + code;
						StringRequest stringRequest = new StringRequest(url,
								new Listener<String>() {
									@Override
									public void onResponse(String arg0) {
										// TODO Auto-generated method stub
										if (arg0.contains("正确")) {
											isTrue_code = true;
											tv_msg_code
													.setVisibility(View.GONE);
											iv_right_code
													.setVisibility(View.VISIBLE);
										} else {
											isTrue_code = false;
											tv_msg_code.setText(arg0.toString());
											tv_msg_code
													.setVisibility(View.VISIBLE);
											iv_right_code
													.setVisibility(View.GONE);
										}

									}
								}, null);
						mQueue.add(stringRequest);
					}
				}
				break;
			case R.id.et_invite:
				invite = et_invite.getText().toString();
				if (invite == null) {
					invite = "";
					isTrue_invite = true;
				} else {
					url = VMConst.REQUEST_URL + "checkInvCode?invCode="
							+ invite;
					StringRequest stringRequest = new StringRequest(url,
							new Listener<String>() {
								@Override
								public void onResponse(String arg0) {
									// TODO Auto-generated method stub
									if (arg0.contains("存在")) {
										isTrue_invite = true;
										iv_right_invite
												.setVisibility(View.VISIBLE);
									} else {
										isTrue_invite = false;
									}

								}
							}, null);
					mQueue.add(stringRequest);
				}
				break;
			default:
				break;
			}
		}
	};

	OnClickListener getCodeListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			invite = et_invite.getText().toString();
			if (invite == null || invite.equals("")) {
				isTrue_invite = true;
			} else {
				String url = VMConst.REQUEST_URL + "checkInvCode?invCode="
						+ invite;
				StringRequest stringRequest = new StringRequest(url,
						new Listener<String>() {
							@Override
							public void onResponse(String arg0) {
								// TODO Auto-generated method stub
								if (arg0.contains("存在")) {
									isTrue_invite = true;
									iv_right_invite.setVisibility(View.VISIBLE);
								} else {
									isTrue_invite = false;
								}

							}
						}, null);
				mQueue.add(stringRequest);
			}
			if (isTrue_name && isTrue_pass && isTrue_phone && isTrue_invite) {
				// TODO Auto-generated method stub
				String mobilephone = et_phone.getText().toString();
				btn_get_code.setEnabled(false);
				timer = new Timer(true);
				mTimerTask = new MyTimerTask(countDown, handler);
				timer.schedule(mTimerTask, 1000, 1000);

				if (mobilephone != null && !mobilephone.equals("")) {
					String url = VMConst.REQUEST_URL
							+ "getMobileCode?mobilephone="
							+ et_phone.getText().toString() + "&deviceId="
							+ StringUtil.DEVICEID;
					StringRequest stringRequest = new StringRequest(url,
							new Listener<String>() {

								@Override
								public void onResponse(String arg0) {
									// TODO Auto-generated method stub
									if (arg0.contains("1")) {
										Toast toast3 = Toast.makeText(
												RegisterActivity.this,
												"正在发送，请稍后", 500);
										toast3.setGravity(Gravity.CENTER, 0, 0);
										toast3.show();
									}
								}
							}, null);
					mQueue.add(stringRequest);
					btn_get_code.setEnabled(false);
					// 发送验证码后禁止输入手机号码
					et_phone.setEnabled(false);
				}

			}
		}
	};

	@SuppressLint("HandlerLeak")
	final Handler handler = new Handler() {
		@SuppressLint("HandlerLeak")
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				String remainTime = msg.obj.toString();
				btn_get_code.setText("重新发送" + remainTime);
				break;

			case 2:
				btn_get_code.setText("重新发送");
				timer.cancel();
				btn_get_code.setEnabled(true);
				break;
			}

			super.handleMessage(msg);
		}
	};

	OnClickListener btnClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			if (et_invite.getText().toString().equals("")
					|| et_invite.getText().toString() == null) {
				isTrue_invite = true;
				invite = "";
			} else {
				invite = et_invite.getText().toString();
				String url = VMConst.REQUEST_URL + "checkInvCode?invCode="
						+ invite;
				StringRequest stringRequest = new StringRequest(url,
						new Listener<String>() {
							@Override
							public void onResponse(String arg0) {
								// TODO Auto-generated method stub
								if (arg0.contains("存在")) {
									isTrue_invite = true;
									iv_right_invite.setVisibility(View.VISIBLE);
								} else {
									isTrue_invite = false;
								}

							}
						}, null);
				mQueue.add(stringRequest);
			}
			if (isTrue_name && isTrue_pass && isTrue_phone && isTrue_code
					&& isTrue_invite) {

				// String username = et_username.getText().toString();
				// String password = et_pass.getText().toString();
				// String phone = et_phone.getText().toString();
				// // String email = et_email.getText().toString();
				// String code = et_code.getText().toString();

				try {
					username = URLEncoder.encode(username, "UTF-8");
					password = URLEncoder.encode(password, "UTF-8");
					phone = URLEncoder.encode(phone, "UTF-8");
					// email = URLEncoder.encode(email, "UTF-8");
					code = URLEncoder.encode(code, "UTF-8");

				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				String url = VMConst.REQUEST_URL + "android_register?username="
						+ username + "&password=" + password + "&phone="
						+ phone + "&code=" + code + "&deviceId="
						+ StringUtil.DEVICEID + "&invCode=" + invite;

				StringRequest registerRequest = new StringRequest(url,
						new Listener<String>() {

							@Override
							public void onResponse(String response) {
								if (response.contains("注册成功")) {
									Intent intent = new Intent(
											RegisterActivity.this,
											LoginActivity.class);
									startActivity(intent);
									RegisterActivity.this.finish();
								} else if (response.contains("验证码")) {
									Toast toast = Toast.makeText(
											RegisterActivity.this, "验证码输入错误",
											Toast.LENGTH_SHORT);
									toast.show();
								} else {
									Toast toast = Toast.makeText(
											RegisterActivity.this, "该用户名已注册",
											Toast.LENGTH_SHORT);
									toast.show();
								}
							}
						}, new ErrorListener() {

							@Override
							public void onErrorResponse(VolleyError error) {
							}

						});

				mQueue.add(registerRequest);
			}

			else {
				Toast toast = Toast.makeText(RegisterActivity.this, "请填写正确信息",
						Toast.LENGTH_SHORT);
				toast.show();
			}
		}
	};

	public boolean isMobileNO(String mobiles) {

		Pattern p = Pattern
				.compile("^((13[0-9])|(15[^4,\\D])|(18[0-3,5-9]))\\d{8}$");

		Matcher m = p.matcher(mobiles);
		return m.matches();
	}

	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		if (ev.getAction() == MotionEvent.ACTION_DOWN) {
			View v = getCurrentFocus();
			if (isShouldHideInput(v, ev)) {

				validateText(v);
				InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
				if (imm != null) {
					imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
				}
			}
			return super.dispatchTouchEvent(ev);
		}
		// 必不可少，否则所有的组件都不会有TouchEvent了
		if (getWindow().superDispatchTouchEvent(ev)) {
			return true;
		}
		return onTouchEvent(ev);
	}

	public boolean isShouldHideInput(View v, MotionEvent event) {
		if (v != null && (v instanceof EditText)) {
			int[] leftTop = { 0, 0 };
			// 获取输入框当前的location位置
			v.getLocationInWindow(leftTop);
			int left = leftTop[0];
			int top = leftTop[1];
			int bottom = top + v.getHeight();
			int right = left + v.getWidth();
			if (event.getX() > left && event.getX() < right
					&& event.getY() > top && event.getY() < bottom) {
				// 点击的是输入框区域，保留点击EditText的事件
				return false;
			} else {
				return true;
			}
		}
		return false;
	}

	/**
	 * imgbtn_search_back 返回按钮监听
	 */
	OnClickListener btn_backListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			onBackPressed();
		}
	};

	public static boolean isLetterDigitOrChinese(String str) {
		Pattern p = Pattern.compile("[A-Z,a-z,0-9,-]*");
		Matcher m = p.matcher(str);
		if (m.matches()) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 手机自带返回按钮监听
	 */
	@Override
	public void onBackPressed() {
		super.onBackPressed();

	}

}
